package tt.dz.appserver.service.business.imp;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.websocket.Session;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;

import tt.dz.appserver.dao.ext.ImagesDao;
import tt.dz.appserver.dao.ext.LabelDao;
import tt.dz.appserver.dao.ext.PushMessageDao;
import tt.dz.appserver.dao.ext.ShareCommentDao;
import tt.dz.appserver.dao.ext.SharesDao;
import tt.dz.appserver.dao.ext.ThumbUpDao;
import tt.dz.appserver.dao.ext.UserInfoDao;
import tt.dz.appserver.entity.dto.push.SystemMessageDto;
import tt.dz.appserver.entity.model.ResultMappingEntity;
import tt.dz.appserver.entity.model.pub.Images;
import tt.dz.appserver.entity.model.pub.Label;
import tt.dz.appserver.entity.model.pub.ShareComment;
import tt.dz.appserver.entity.model.pub.Shares;
import tt.dz.appserver.entity.model.pub.ThumbUp;
import tt.dz.appserver.entity.model.push.PushMessage;
import tt.dz.appserver.entity.model.user.UserInfo;
import tt.dz.appserver.entity.vo.PushMessageNumberVO;
import tt.dz.appserver.entity.vo.PushMessageVO;
import tt.dz.appserver.entity.vo.ShareCommentInfoVo;
import tt.dz.appserver.entity.vo.ShareImageVo;
import tt.dz.appserver.entity.vo.ShareLabelVo;
import tt.dz.appserver.entity.vo.SharesVo;
import tt.dz.appserver.entity.vo.user.UserBaseVo;
import tt.dz.appserver.service.business.PushMessageService;
import tt.dz.appserver.service.business.ShareService;
import tt.dz.appserver.util.JpushUtils;
import tt.dz.appserver.util.ReflectUtils;
import tt.dz.appserver.util.Result;
import tt.dz.appserver.util.WebSocketUtils;
import tt.dz.appserver.util.date.DateUtil;
import tt.dz.appserver.util.encoding.EncodingUtils;
import tt.dz.appserver.util.enums.ImageAssociatedType;
import tt.dz.appserver.util.enums.ImageType;
import tt.dz.appserver.util.enums.Response;
import tt.dz.appserver.util.enums.ThumbUpType;
import tt.dz.appserver.util.enums.Valid;
import tt.dz.appserver.util.enums.push.PushBusinessCode;

/**
 * 消息推送实现
 * @author Administrator
 *
 */
public class PushMessageServiceImpl implements PushMessageService {
	

	@Resource
	private PushMessageDao messageDao;
	@Resource
	private UserInfoDao userInfoDao;
	private final static Logger LOG = Logger.getLogger("[消息推送管理接口]:");
	
	@Override
	public ResultMappingEntity messageList(PushMessage pushMessage, int pageNo) {
		
		List<PushMessage> messages=messageDao.findList(pushMessage, pageNo);
		
		Integer number=messageDao.number();
		
		
		List<PushMessageVO> messagesVOs= new ArrayList<PushMessageVO>();
		for(PushMessage message:messages){
			PushMessageVO messagesVO = new PushMessageVO();
			messagesVO.setPushId(message.getPush_id());
			messagesVO.setTitle(message.getTitle());
			messagesVO.setContent(message.getContent());
			messagesVO.setEditDate(message.getEdit_date());
			messagesVO.setPushDate(message.getPush_date());
			messagesVO.setState(message.getState());
			messagesVO.setDelayDate(message.getDelay_date());
			messagesVO.setMessageType(message.getMessage_type());
			messagesVO.setScope(message.getScope());
			messagesVO.setRegStartDate(message.getReg_start_date());
			messagesVO.setRegEndDate(message.getReg_end_date());
			messagesVO.setAccountSex(message.getAccount_sex());
			messagesVO.setPushUserId(message.getPush_user_id());
			messagesVO.setPushOperator(message.getPush_operator());
			messagesVO.setSysCode(message.getSys_code());
			messagesVO.setValidFlag(message.getValid_flag());
			messagesVO.setIsPush(message.getIs_push());
			messagesVO.setOnLineUser(message.getOn_line_user());
			
			messagesVOs.add(messagesVO);
			
		}
		PushMessageNumberVO  vo= new PushMessageNumberVO();
		vo.setNumber(number);
		vo.setMessagesVOs(messagesVOs);
		return Result.responseBody(Response.SUCCESS.getCode(), Response.SUCCESS.getMsg(), vo);
	}
	
	@Override
	public ResultMappingEntity messageDetail(String pushId) {

		PushMessage message = messageDao.findSharesDetailByPushId(pushId);

		
		return Result.responseBody(Response.SUCCESS.getCode(), Response.SUCCESS.getMsg(), message);
	}

	
	@Override
	public ResultMappingEntity updateMessage(PushMessage message) {

		ResultMappingEntity resultMappingEntity = null;
		
			// 
		  messageDao.save(message);
			resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg());	
		return resultMappingEntity;
	}



	@Override
	public ResultMappingEntity deleteMessage(String pushId) {
		
		PushMessage message = new PushMessage();
		message.setPush_id(pushId);
		messageDao.LogicDelete(message);
		return Result.responseBody(Response.SUCCESS.getCode(), Response.SUCCESS.getMsg());
	}
	
	/**
	 * 新增/更新消息推送
	 */
	@Override
	public ResultMappingEntity saveMessage(String pushId, String title, String content, String editDate,
			String pushDate, int state, String delayDate, int messageType, int scope, String regStartDate,
			String regEndDate, int accountSex, String pushUserId, String pushOperator, String sysCode, int isPush,
			int onLineUser) {
		
		ResultMappingEntity resultMappingEntity = null;
		PushMessage message = new PushMessage();
		message.setTitle(title);
		message.setContent(content);
		if(editDate != null && editDate.length() > 0){
			message.setEdit_date(DateUtil.parseStringToDate(editDate));
		}else{
			message.setEdit_date(new Date());
		}
		if(pushDate != null && pushDate.length() > 0){
			message.setPush_date(DateUtil.parseStringToDate(pushDate));
		}else{
			message.setPush_date(new Date());
		}
		message.setState(state);
		if(delayDate != null && delayDate.length() > 0)
			message.setDelay_date(DateUtil.parseStringToDate(delayDate));
		else
			message.setDelay_date(new Date());
		message.setMessage_type(messageType);
		message.setScope(scope);
		if(regStartDate != null && regStartDate.length() > 0)
			message.setReg_start_date(DateUtil.parseStringToDate(regStartDate));
		else{
			message.setReg_start_date(new Date());
		}
		if(regEndDate != null && regEndDate.length() > 0)
			message.setReg_end_date(DateUtil.parseStringToDate(regEndDate));
		else{
			message.setReg_end_date(new Date());
		}
		message.setAccount_sex(accountSex);
		message.setPush_user_id(pushUserId);
		message.setPush_operator(pushOperator);
		message.setSys_code(sysCode);
		message.setValid_flag(1);
		message.setIs_push(isPush);
		message.setOn_line_user(onLineUser);
		message.setUser_id_list("");
		int	result=0;
		//
		if(pushId.trim().isEmpty()){
			message.setPush_id(DateUtil.getDateTimeLong()+EncodingUtils.getRandomIntegerString(4));
			result = messageDao.save(message);
			LOG.info("保存消息推送");
		
		}else{
			message.setPush_id(pushId);
			result = messageDao.update(message);
			LOG.info("更新消息推送");
		}
		//保存数据成功且推送方式为及时推送
		if(result>0&&state == 1){
			
			//推送实体类  
			SystemMessageDto  systemMessage= new SystemMessageDto();
			systemMessage.setTitle(message.getTitle());
			systemMessage.setContent(message.getContent());
			systemMessage.setIsRead("1");
			systemMessage.setTime(DateUtil.getDateTime());
			systemMessage.setId(message.getPush_id());
			Map<String, String> pushData;
			try {
				pushData = ReflectUtils.objectParseMap(systemMessage);
				
			} catch (Exception e) {
				e.printStackTrace();
				return resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg());	
			} 
			Map<String, String> pushMap = new HashMap<String, String>();
			pushMap.put("action", PushBusinessCode.SYSTEM.getCode());
			pushMap.put("data", JSON.toJSONString(pushData));
			String pushJsonString=JSON.toJSONString(pushMap);
			//获取所以websocet连接并且推送
			Map<String, Session> clients = WebSocketUtils.clients;
			for(String key : clients.keySet()){
				WebSocketUtils.sendMessage(key, pushJsonString);
			}
			//推送所有极光  当前没有做优化，当前测试完成后做线程池或者队列
			UserInfo userInfo = new UserInfo();
			userInfo.setValid_flag(1);
			List<UserInfo> userInfos = userInfoDao.getAllUsers(userInfo);
			for(UserInfo user:userInfos){
				if(user.getJpush_id()!=null&&user.getJpush_id().trim().length()>1){
					try{
						JpushUtils.pushMsgByRegId(user.getJpush_id(), systemMessage.getTitle(), pushMap);
					}catch(Exception e){
						LOG.error("推送失败");
						LOG.error(e.getStackTrace());
					}
					
				}
			}	
			//TODO 测试
			
			//JpushUtils.pushMsgByRegId("190e35f7e04320ee4b5", systemMessage.getTitle(), pushMap);
			
			resultMappingEntity = Result.responseBody(Response.SUCCESS.getCode(), Response.SUCCESS.getMsg());
		//延时推送	
		}else if(result>0&&state == 3){
			//TODO 二期优化 优化
			resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg());	
		//保存草稿	
		}else if(result>0&&state == 2){
			resultMappingEntity = Result.responseBody(Response.SUCCESS.getCode(), Response.SUCCESS.getMsg());
		}else{
			resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg());	
		}		
	return resultMappingEntity;
	}
	
	
	
}
